var gulp = require("gulp");
var $ = require('gulp-load-plugins')();
var ts = require("gulp-typescript");
var concat = require('gulp-concat');
var rimraf = require("rimraf");
var jasmine = require('gulp-jasmine');
var tsProject = ts.createProject('tsconfig.json');
var tsTestProject = ts.createProject('./test/tsconfig.json');

var paths = {
    scripts:[
        'dist/src/*.js'
    ],
    test:[
        'spec/*.js'
    ],
    testRequire:[
        'dist/libs/angular/angular.js',
        'dist/libs/mustache.js/mustache.js'
    ]
}

gulp.task("default",function(){
    var tsResult = tsProject.src()
        .pipe(ts(tsProject));
   return tsResult.js.pipe(gulp.dest('dist/src'));
});

gulp.task("test:build",function(){
    var tsResult2 = tsTestProject.src()
        .pipe(ts(tsTestProject));
    return tsResult2.js.pipe(gulp.dest('spec'));
});

//清除dist/src下文件
gulp.task("clean",function(cb){
    rimraf('dist/src',cb);
});

gulp.task('start:server:test', function () {
    $.connect.server({
        root: ['spec', 'dist'],
        livereload: true,
        host: "0.0.0.0",
        port: 5001
    });
});

gulp.task('test:core', function () {
    var testToFiles = paths.testRequire.concat(paths.scripts, paths.test);
    console.info(testToFiles);
    return gulp.src(testToFiles)
      .pipe($.karma({
          configFile: 'karma.conf.js',
          autoWatch: true,
          singleRun: false,
          action: 'watch'
      })).on('error', function (err) {
          // Make sure failed tests cause gulp to exit non-zero
          console.log("Failed with: ", err);
          process.exit(-1); //instead of erroring the stream, end it
      });
});

gulp.task('test', ['default','test:build','start:server:test', 'test:core'], function () {
    process.exit(0);
});